<template>
  <div class="JNPF-common-layout">
    <div class="JNPF-common-layout-center">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent label-width="80px" label-position="left">
          <el-col :span="8">
            <el-form-item label="申请日期" style="height:30px">
            <el-date-picker v-model="alarmdate" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" />
          </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单据编号">
            <el-input v-model="listQuery.fbillno" clearable 
              placeholder="请输入单据编号" />
          </el-form-item>
          </el-col>
          <template v-if="showAll">
            <el-col :span="8">
            <el-form-item label="单据状态">
              <el-select v-model="listQuery.fbillstate" class="filter-item" clearable placeholder="请选择单据状态">
                <el-option v-for="item in fbillstateOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="存放地点">
              <el-select style="display: inline-block" clearable filterable v-model="listQuery.fpointNo"
              class="filter-item" placeholder="请选择存放地点">
              <el-option v-for="item in getListfpointNo" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item class="searchOne" label="申请人员">
              <el-select style="display: inline-block" clearable filterable v-model="listQuery.fuseuser"
              class="filter-item" placeholder="请选择申请人员">
              <el-option v-for="item in getListfuseuser" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            </el-form-item>
          </el-col>
          </template>
          <el-col :span="8">
            <el-form-item>
              <el-button type="primary" @click="handleFilter">查找</el-button>
              <el-button type="success" @click="handleCreate">添加</el-button>
              <el-button type="text" icon="el-icon-arrow-down" @click="showAll=true"
                v-if="!showAll">展开</el-button>
              <el-button type="text" icon="el-icon-arrow-up" @click="showAll=false" v-else>
                收起</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JNPF-common-layout-main JNPF-flex-main">
       <!-- 查询结果 -->
        <JNPF-table  v-loading="listLoading" :data="list" >
          <el-table-column :width="buttonColor.operationThree" align="center" label="操作" class-name="small-padding">
            <template slot-scope="scope">
              <el-button type="text" @click="handleUpdate(scope.row)">编辑</el-button>
              <el-button type="text" v-if="scope.row.fbillstate === 1" @click="handleDelete(scope.row)">删除</el-button>
              <el-button type="text" v-if="scope.row.fbillstate === 1" @click="audit(scope.row)">确认</el-button>
            </template>
          </el-table-column>
          <el-table-column :width="buttonColor.line" :index="indexMethod" align="center" label="序号" type="index" />
          <el-table-column :width="buttonColor.billno" align="left" label="单据编号" prop="fbillno" />
          <el-table-column :formatter="formatfpointNo" align="left" label="存放地点" prop="fpointNo" />
          <el-table-column :width="buttonColor.user" :formatter="formatfuseuser" align="left" label="申请人员"
            prop="fuseuser" />
          <el-table-column :width="buttonColor.date" :formatter="datetimeFormat" align="left" label="申请日期"
            prop="fusedate" />
          <el-table-column :width="buttonColor.date" :formatter="datetimeFormat" align="left" label="使用日期"
            prop="fplanusedate" />
          <el-table-column :width="buttonColor.date" :formatter="timeFormat" align="left" label="开始时间"
            prop="frealbegtime" />
          <el-table-column :width="buttonColor.date" :formatter="timeFormat" align="left" label="结束时间"
            prop="frealendtime" />
          <el-table-column :width="buttonColor.num" align="center" label="人数" prop="fmancount" />
          <el-table-column :width="buttonColor.state" align="left" label="单据状态" prop="fbillstate">
            <template slot-scope="scope">
              <span v-if="scope.row.fbillstate === 1" :style="{ color: buttonColor.order }">{{ scope.row.fbillstate |
                  statusFilter
              }}</span>
              <span :style="{ color: buttonColor.approval }" v-else-if="scope.row.fbillstate === 2">{{
                  scope.row.fbillstate | statusFilter
              }}</span>
              <span :style="{ color: buttonColor.refused }" v-else-if="scope.row.fbillstate === 3">{{
                  scope.row.fbillstate | statusFilter
              }}</span>
              <span :style="{ color: buttonColor.rcancel }" type="info" v-else>{{
                  scope.row.fbillstate | statusFilter
              }}</span>
            </template>
          </el-table-column>
        </JNPF-table>
        <paginations
        :total="total"
        :page.sync="listQuery.currentPage"
        :limit.sync="listQuery.pageSize"
        />
      </div>
    </div>
    <!-- 添加或修改对话框 -->
    <el-dialog 
    :fullscreen="true"
       :close-on-click-modal="false" 
       :before-close="handleClose" 
       :title="textMap[dialogStatus]"
       :visible.sync="dialogFormVisible">
       <el-tabs type="border-card">
        <el-tab-pane label="头表" :style="{height:screenHeight-230+'px'}">
          <el-row class="JNPF-common-search-box" :gutter="16">
            <el-form @submit.native.prevent label-width="80px" label-position="left" ref="dataForm" :rules="rules" :model="dataForm" >
              <el-col :span="6">
                <el-form-item class="required" label="单据编号" prop="fbillno">
                  <el-input disabled v-model="dataForm.fbillno" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item class="required" label="申请日期" prop="fusedate">
                  <el-date-picker disabled v-model="dataForm.fusedate" type="date"/>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item class="required" label="单据状态" prop="fbillstate">
                  <el-select disabled v-model="dataForm.fbillstate" class="filter-item" clearable placeholder="请选择单据状态">
                    <el-option v-for="item in fbillstateOptions" :key="item.value" :label="item.label"
                      :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item class="required" label="存放地点" prop="fpointNo">
                  <el-select @change="pointChange" style="display: inline-block" clearable filterable
                  v-model="dataForm.fpointNo" class="filter-item" placeholder="请选择存放地点">
                  <el-option v-for="item in getListfpointNo" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="申请人员" prop="fuseuser">
                  <el-select :disabled="dialogStatus != 'create'" clearable filterable v-model="dataForm.fuseuser"
                   placeholder="请选择申请人员">
                  <el-option v-for="item in getListfuseuser" :key="item.value" :label="item.label"
                    :value="item.value" />
                </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item class="required" label="申请人数" prop="fmancount">
                  <el-input class="number" maxlength="5" onkeyup="this.value=this.value.replace(/[^\d]/g,'');"
                    v-model.number="dataForm.fmancount" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item class="required" label="使用日期" prop="fplanusedate">
                  <el-date-picker v-model="dataForm.fplanusedate" :picker-options="test" type="date" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item class="required" label="开始时间" prop="frealbegtime">
                  <el-time-picker v-model="dataForm.frealbegtime" placeholder="开始时间">
                  </el-time-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item class="required" label="结束时间" prop="frealendtime">
                  <el-time-picker v-model="dataForm.frealendtime" placeholder="结束时间">
                  </el-time-picker>
                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item class="text" label="备注" prop="fexplanation">
                  <el-input v-model="dataForm.fexplanation" />
                </el-form-item>
              </el-col>
              <el-col :span="6"></el-col>
              <el-col :span="6"></el-col>
            </el-form>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="明细表">
          <JNPF-table :height="screenHeight-230" v-loading="listLoading" :data="dataForm.details" >
                <el-table-column :width="buttonColor.line" align="center" label="行号" prop="fline" />
                <el-table-column width="220" align="left" label="容器标签" prop="frfidbarcode"></el-table-column>
                <el-table-column width="200" align="left" label="物料编号" prop="fgoodno">
                  <template slot-scope="scope">
                    <el-input 
                      v-model="scope.row.fgoodno" 
                      v-direction="{ x: 0, y: scope.$index,type:3}"
                    >
                      <el-button slot="append" icon="el-icon-search" @click="searchDialogMaterial"></el-button>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column width="100" :formatter="formatfgoodno" align="left" label="物料名称" prop="fgoodname" />
                <el-table-column align="center" label="剩余量" prop="fqty" />
                <el-table-column align="center" label="申请量" prop="fretqty">
                   <template slot-scope="scope">
                    <el-input 
                      v-model="scope.row.fretqty" 
                      v-direction="{ x: 1, y: scope.$index,type:3}"
                    >
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column :formatter="formatfboxbarcode" align="left" label="储物仓" prop="fboxbarcode" />
                <el-table-column :formatter="formatfcabbarcode" align="left" label="储物柜" prop="fcabbarcode" />
                <el-table-column v-if="isshow" :width="buttonColor.operationTwo" align="center" label="操作"
                  class-name="small-padding">
                  <template slot-scope="scope">
                    <el-button type="text" @click="handleDelete1(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </JNPF-table>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <div>
          <el-button type="info" @click="cancel()">取消</el-button>
          <el-button type="primary" v-if="dialogStatus == 'create'"@click="createData">确定</el-button>
          <el-button type="primary" v-else  @click="updateData">确定</el-button>
        </div>
      </span>
       </el-dialog>
       <userDialog :searchVisibleuse.sync="searchVisibleuse" :fsiteNo.sync="userDialogFsiteNo" :tableColor="tableColor"
      @userDialog="userDialogValue" />
    <labDialog :searchVisiblelab.sync="searchVisiblelab" :fsiteNo.sync="labDialogFsiteNo" :tableColor="tableColor"
      @labDialog="labDialogValue" />
    <materialBox :materialIdVisible.sync="materialIdVisible" :fsiteNo.sync="materialFsiteNo" :tableColor="tableColor"
      :fpointNo.sync="materialFpointNo" @materialDialog="materialDialogValue" />
  </div>
</template>
<script>
import {
  listuseHead,
  createuseHead,
  updateuseHead,
  deleteuseHead,
  checkAdd
} from "@/api/useHead2";
import { listtsWarehouse } from "@/api/tsWarehouse";
import { listtsCabinet } from "@/api/tsCabinet";
import Pagination from "@/components/Pagination";
import UserDialog from "@/components/UserDialog";
import LabDialog from "@/components/LabDialog";
import MaterialBox from "@/components/MaterialBox";
import WarehouseDialog from "@/components/WarehouseDialog";
import CabinetDialog from "@/components/CabinetDialog";
import moment from "moment";
import { tableColor, titleColor, buttonColor } from "@/filters/index";
import { getListArea, getFbillno, checkBiz } from "@/api/area";

const statusMap = {
  1: "预约中",
  2: "已批准",
  3: "不核准",
  8: "已取消",
};

export default {
  name: "ITcUseHead",
  components: {
    Pagination,
    UserDialog,
    LabDialog,
    MaterialBox,
    WarehouseDialog,
    CabinetDialog,
  },
  filters: {
    statusFilter(type) {
      return statusMap[type];
    },
  },
  data() {
    return {
      isAdd1: true,
       screenHeight: document.body.clientHeight,
      panelHeight: 0,
      cabDialogFsiteNo: null,
      wareDialogFsiteNo: null,
      materialFpointNo: null,
      isshow: false,
      test: {
        disabledDate(date) {
          let zero = new Date().setHours(0, 0, 0, 0);
          if (date.getTime() < zero) {
            return true;
          }
          return false;
        }
      },
      buttonColor: buttonColor,
      listCabinet: [],
      cabinetVisible: false,
      listWarehouse: [],
      warehouseVisible: false,
      materialIdVisible: false,
      materialFsiteNo: null,
      labFlag: null,
      searchVisiblelab: false,
      labDialogFsiteNo: null,

      userFlag: null,
      searchVisibleuse: false,
      userDialogFsiteNo: null,
      goodAllList: [],
      dialogFormVisible1: false,
      dialogStatus1: null,
      detailsTmp: [],
      listTmp: [],
      dataForm1: {
        fbillno: undefined,
        fline: undefined,
        fgoodno: undefined,
        fgoodname: undefined,
        fbuyprice: undefined,
        fqty: undefined,
        fretqty: undefined,
        fuseqty: undefined,
        fboxbarcode: undefined,
        fboxbarcodeName: undefined,
        fcabbarcode: undefined,
        fcabbarcodeName: undefined,
        fmemo: undefined,
        frfidbarcode: undefined,
      },
      flineList: [],
      selectList: [],

      getListfuseuser: [],
      getListfpointNo: [],
      list: null,
      total: 0,
      listLoading: true,
      alarmdate: null,
      listQuery: {
        currentPage: 1,
        page: 1,
        limit: 20,
        fsiteNo: this.$store.state.user.fsiteNo,
        fuseuser: undefined,
        fusedate: undefined,
        fplanusedate: undefined,
        ftakedateStart: undefined,
        ftakedateEnd: undefined,
        fpointNo: undefined,
        fmancount: undefined,
        fplanbegtime: undefined,
        fplanendtime: undefined,
        frealbegtime: undefined,
        frealendtime: undefined,
        fexplanation: undefined,
        faudituser: undefined,
        fauditdate: undefined,
        fauditnote: undefined,
        fupddate: undefined,
        foperator: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        fbilltype: 1,
        sort: "create_time",
        order: "desc",
      },
      dataForm: {
        fbillno: undefined,
        fsiteNo: undefined,
        fuseuser: undefined,
        fusedate: undefined,
        fplanusedate: undefined,
        fpointNo: undefined,
        fmancount: undefined,
        fplanbegtime: undefined,
        fplanendtime: new Date(),
        frealbegtime: undefined,
        frealendtime: undefined,
        fexplanation: undefined,
        faudituser: undefined,
        fauditdate: undefined,
        fauditnote: undefined,
        fupddate: undefined,
        foperator: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        fbilltype: undefined,
        id: undefined,
        details: [],
      },
      tableColor: tableColor,
      showAll:false,
      titleColor: titleColor,
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建",
      },
      dialogStatusSon: '',
      rules: {
        fsiteNo: [{ required: true, message: "客户名称不能为空" }],
        fuseuser: [{ required: true, message: "申请人员不能为空" }],
        fusedate: [{ required: true, message: "申请日期不能为空" }],
        fplanusedate: [{ required: true, message: "使用日期不能为空" }],
        frealbegtime: [{ required: true, message: "开始时间不能为空" }],
        frealendtime: [{ required: true, message: "结束时间不能为空" }],
        fpointNo: [{ required: true, message: "存放地点不能为空" }],
        fmancount: [
          { required: true, message: "申请人数不能为空" },
          // { type: "number", message: "申请人数必须为数字值" },
        ],
        fbillstate: [{ type: "number", message: "单据状态必须为数字值" }],
      },
      rules1: {
        fline: [
          { required: true, message: "行号不能为空" },
          { type: "number", message: "行号必须为数字值" },
        ],
        frfidbarcode: [{ required: true, message: "容器标签不能为空" }],
        fgoodno: [{ required: true, message: "物料编号不能为空" }],
        fqty: [{ required: true, message: "剩余量不能为空" }],
        fuseqty: [{ required: true, message: "使用量不能为空" }],
        fretqty: [{ required: true, message: "申请量不能为空" }],
        fboxbarcode: [{ required: true, message: "储物仓不能为空" }],
        fcabbarcode: [{ required: true, message: "储物柜不能为空" }],
      },
      fbillstateOptions: [
        { value: 1, label: "预约中" },
        { value: 2, label: "已批准" },
        { value: 3, label: "不核准" },
        { value: 8, label: "已取消" },
      ],
    };
  },
  created() {
    this.keyCode();
    this.alarmdate = [
      new Date(),
      new Date(),
    ];
    this.panelHeight = document.documentElement.clientHeight - 335
    this.getList();
    // 地点
    getListArea({ flag: 10, arg1: this.$store.state.user.fsiteNo })
      .then((response) => {
        this.getListfpointNo = response.data.data.list;
      })
      .catch(() => {
        this.getListfpointNo = [];
      });
    // 人员弹出框
    getListArea({ flag: 13, arg1: this.$store.state.user.fsiteNo })
      .then((response) => {
        this.getListfuseuser = response.data.data.list;
      })
      .catch(() => {
        this.getListfuseuser = [];
      });

    // 物料
    getListArea({ flag: 31 })
      .then((response) => {
        this.goodAllList = response.data.data.list;
      })
      .catch(() => {
        this.goodAllList = [];
      });
    // 储物仓列表
    listtsWarehouse({ limit: -1 })
      .then((response) => {
        this.listWarehouse = response.data.data.list;
      })
      .catch(() => {
        this.listWarehouse = [];
      });
    // 储物柜列表
    listtsCabinet({ limit: -1 })
      .then((response) => {
        this.listCabinet = response.data.data.list;
      })
      .catch(() => {
        this.listCabinet = [];
      });
  },
  methods: {
    keyCode() {
      let direction = this.$getDirection();
      let _this=this;
      direction.on("keyup", function (e, val) {
        if (e.keyCode === 13) {
          if(val.y==_this.dataForm.details.length-1)
          {
            _this.addrow(res=>{
               direction.next();
            })
          }
          else
          {
           direction.next();
          }
        }
        if (e.keyCode === 37) {
          direction.previous();
        }
        if (e.keyCode === 38) {
          direction.previousLine();
        }
        if (e.keyCode === 40) {
          direction.nextLine();
        }
        if (e.keyCode == 39) {
          direction.next();
        }
      });
    },
    //
    addrow(callback){
      this.dataForm.details.push({
        fline:this.dataForm.details.length+1,
        frfidbarcode:'',
        fgoodno:'',
        fgoodname:"",
        fqty:"",
        fretqty:"",
        fboxbarcode:"",
        fcabbarcode:""
      })
      callback(200)
    },
    //
    datetimeFormat(row, column) {
      const date = row[column.property];
      if (date === undefined || date === null) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD");
    },
    timeFormat(row, column) {
      const date = row[column.property];
      if (date === undefined || date === null) {
        return "";
      }
      return moment(date).format("HH:mm:ss");
    },
    formatDate: function (date) {
      if (typeof date === "object") {
        var ym;
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        var d = date.getDate();
        if (m < 10) {
          m = "0" + m;
        }
        if (d < 10) {
          d = "0" + d;
        }
        ym = "" + y + m + d;
        return ym;
      } else {
        return date;
      }
    },
    // 储物仓名称
    formatfboxbarcode: function (row, column) {
      if (this.listWarehouse) {
        for (let i = 0; i < this.listWarehouse.length; i++) {
          if (row.fboxbarcode == this.listWarehouse[i].fequipmentbarcode) {
            return this.listWarehouse[i].fequipmenttag;
          }
        }
        return "";
      } else {
        return "";
      }
    },

    // 储物柜名称
    formatfcabbarcode: function (row, column) {
      if (this.listCabinet) {
        for (let i = 0; i < this.listCabinet.length; i++) {
          if (row.fcabbarcode == this.listCabinet[i].fequipmentbarcode) {
            return this.listCabinet[i].fequipmenttag;
          }
        }
        return "";
      } else {
        return "";
      }
    },

    // 物料
    formatfgoodno: function (row, column) {
      if (this.goodAllList.length > 0) {
        for (let i = 0; i < this.goodAllList.length; i++) {
          if (row.fgoodno === this.goodAllList[i].value) {
            return this.goodAllList[i].label;
          }
        }
        return "";
      } else {
        return "";
      }
    },
    // 物料弹出框
    searchDialogMaterial() {
      this.materialFpointNo = this.dataForm.fpointNo;
      this.materialFsiteNo = this.dataForm.fsiteNo;
      this.materialIdVisible = true;
    },

    // 物料弹出框
    materialDialogValue(value) {
      this.handleUpdate1()
      this.dataForm1.fgoodno = value.data.fgoodno;
      this.dataForm1.fgoodname = value.data.fgoodname;
      this.dataForm1.fbuyprice = value.data.fbuyprice;
      if (value.data.fqty) {
        this.dataForm1.fqty = value.data.fqty;
      } else {
        this.dataForm1.fqty = 0;
      }
      this.dataForm1.fuseqty = 0;
      this.dataForm1.fboxbarcode = value.data.fboxbarcode;
      this.dataForm1.fcabbarcode = value.data.fcabbarcode;
      this.dataForm1.frfidbarcode = value.data.frfidbarcode;
      this.dataForm1.fboxbarcodeName = this.formatfboxbarcode(value.data)
      this.dataForm1.fcabbarcodeName = this.formatfcabbarcode(value.data)
      this.dataForm1.fretqty = ''
    },
    // 搜索地点弹出框
    searchDialoglab(value) {
      this.labFlag = value;
      if (value === "add") {
        this.labDialogFsiteNo = this.dataForm.fsiteNo;
      } else {
        this.labDialogFsiteNo = this.listQuery.fsiteNo;
      }
      this.searchVisiblelab = true;
    },

    // 地点弹出框返回值
    labDialogValue(value) {
      if (this.labFlag === "add") {
        this.dataForm.fpointNo = value.lab.fpointNo;
        this.dataForm.details = [];
      } else {
        this.listQuery.fpointNo = value.lab.fpointNo;
      }
    },

    // 地点改变
    pointChange() {
      this.dataForm.details = [];
    },

    // 地点
    formatfpointNo: function (row, column) {
      if (this.getListfpointNo) {
        for (let i = 0; i < this.getListfpointNo.length; i++) {
          if (row.fpointNo === this.getListfpointNo[i].value) {
            return this.getListfpointNo[i].label;
          }
        }
        return "";
      } else {
        return "";
      }
    },
    // 搜索人员弹出框
    searchDialoguse(value) {
      this.userFlag = value;
      if (value === "add") {
        this.userDialogFsiteNo = this.dataForm.fsiteNo;
      } else {
        this.userDialogFsiteNo = this.listQuery.fsiteNo;
      }
      this.searchVisibleuse = true;
    },

    // 人员弹出框返回值
    userDialogValue(value) {
      if (this.userFlag === "add") {
        this.dataForm.fuseuser = value.user.id.toString();
      } else {
        this.listQuery.fuseuser = value.user.id.toString();
      }
    },

    // 人员
    formatfuseuser: function (row, column) {
      if (this.getListfuseuser) {
        for (let i = 0; i < this.getListfuseuser.length; i++) {
          if (row.fuseuser == this.getListfuseuser[i].value) {
            return this.getListfuseuser[i].label;
          }
        }
        return "";
      } else {
        return "";
      }
    },
    getList() {
      this.listQuery.ftakedateStart =
        this.alarmdate == null ? null : this.formatDate(this.alarmdate[0]);
      this.listQuery.ftakedateEnd =
        this.alarmdate == null ? null : this.formatDate(this.alarmdate[1]);
      this.listLoading = true;
      listuseHead(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    resetForm() {
      this.dataForm = {
        fsiteNo: undefined,
        fuseuser: undefined,
        fusedate: undefined,
        fplanusedate: undefined,
        fpointNo: undefined,
        fmancount: undefined,
        fplanbegtime: undefined,
        fplanendtime: new Date(),
        frealbegtime: undefined,
        frealendtime: undefined,
        fexplanation: undefined,
        faudituser: undefined,
        fauditdate: undefined,
        fauditnote: undefined,
        fupddate: undefined,
        foperator: undefined,
        fcheckdate: undefined,
        fcheckuser: undefined,
        fbillstate: undefined,
        id: undefined,
        details: [],
      };
    },
    resetForm1() {
      this.dataForm1 = {
        fbillno: undefined,
        fline: undefined,
        fgoodno: undefined,
        fgoodname: undefined,
        fbuyprice: undefined,
        fqty: undefined,
        fretqty: undefined,
        fuseqty: undefined,
        fboxbarcode: undefined,
        fboxbarcodeName: undefined,
        fcabbarcode: undefined,
        fcabbarcodeName: undefined,
        fmemo: undefined,
        frfidbarcode: undefined,
      }
    },
    handleCreate() {
      this.isshow = true
      this.resetForm();
      // 单据编号
      getFbillno({ flag: 2026 })
        .then((response) => {
          if (response) {
            this.dataForm.fbillno = response.data.data;
            this.dialogFormVisible = true;
          }
        })
        .catch(() => {
          this.dataForm.fbillno = "";
        });
      this.dataForm.fbillstate = 1;
      this.dataForm.fusedate = new Date();
      this.dataForm.fsiteNo = this.$store.state.user.fsiteNo;
      this.dataForm.fuseuser = this.$store.state.user.id.toString();
      this.dataForm.fmancount = 1;
      this.dataForm.fplanusedate = new Date();
      this.dataForm.frealbegtime = new Date();
      let temp = this.timestampTime(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1)
      this.dataForm.frealendtime = this.parserDate(temp)
      // const day3 = new Date();
      // 使用日期默认D+1
      // day3.setTime(day3.getTime() + 24 * 60 * 60 * 1000);
      // const tem = day3.getFullYear() + "-" + (day3.getMonth() + 1) + "-" + day3.getDate();
      // this.dataForm.fplanusedate = this.parserDate(tem);
      this.dialogStatus = "create";
      // 子表1
      this.handleUpdate1()
      this.resetForm1();
      this.dataForm1.fline = 1
      this.dataForm1.fretqty = ''
      this.addrow();
    },
    timestampTime(timestamp) {
      var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-';
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      var D = date.getDate() + ' ';
      var h = date.getHours() + ':';
      var m = date.getMinutes() + ':';
      var s = date.getSeconds();
      return Y + M + D + h + m + s;
    },
    parserDate(date) {
      var t = Date.parse(date);
      if (!isNaN(t)) {
        return new Date(Date.parse(date.replace(/-/g, "/")));
      }
    },
    year(date) {
      var ym;
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      var d = date.getDate();
      if (m < 10) {
        m = "0" + m;
      }
      if (d < 10) {
        d = "0" + d;
      }
      ym = "" + y + "-" + m + "-" + d;
      return ym;
    },
    hour(date) {
      var ym;
      var h = date.getHours();
      var ms = date.getMinutes();
      var s = date.getSeconds();
      ym = "" + h + ":" + ms + ":" + s;
      return ym;
    },
    createData() {
      this.$refs["dataForm"].validate((valid) => {
        if (this.dataForm.frealendtime >= this.dataForm.frealbegtime) {
          if (valid) {
            this.dataForm.frealbegtime = this.parserDate(
              this.year(this.dataForm.fplanusedate) +
              " " +
              this.hour(this.dataForm.frealbegtime)
            );
            this.dataForm.frealendtime = this.parserDate(
              this.year(this.dataForm.fplanusedate) +
              " " +
              this.hour(this.dataForm.frealendtime)
            );
            this.dataForm.fbilltype = 1
            createuseHead(this.dataForm)
              .then((response) => {
                this.list.unshift(response.data.data);
                this.dialogFormVisible = false;
                this.$notify.success({
                  title: "成功",
                  message: "添加物料申请主表成功",
                });
                this.selectList = [];
                this.flineList = [];
              })
              .catch((response) => {
                this.$notify.error({
                  title: "失败",
                  message: response.data.data,
                });
              });
          }
        }
        else {
          this.$notify.error({
            title: "失败",
            message: '结束时间不能小于开始时间',
          });
        }
      });
      // 每天添加一次
      // checkAdd({ userId: this.dataForm.fuseuser,fplanusedate: this.formatDate(this.dataForm.fplanusedate)})
      //   .then((response) => {
      //     if (response) {
      //       if(response.data.data){


      //       }else{
      //         this.$notify.error({
      //             title: "提示",
      //             message: '每天只能添加一次',
      //           });
      //       }
      //     }
      //   })
      //   .catch(() => {
      //   });
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row);
      this.dialogStatus = "update";
      this.dataForm.fplanendtime=new Date(),
      this.dataForm.fplanbegtime=new Date(),
      this.dialogFormVisible = true;
      this.addrow();
      this.detailsTmp = [];
      this.listTmp = row;
      row.details.forEach((v) => {
        this.detailsTmp.push(v);
        this.selectList.push(v.fgoodno);
        this.flineList.push(v.fline);
      });
      var end = row.details[row.details.length - 1];
      this.indexs = end.fline + 1;
      if (row.fbillstate == 2) {
        this.isshow = false;
      }
      else {
        this.isshow = true
      }
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });


      // 子表1
      this.handleUpdate1()
      this.resetForm1();
      this.dataForm1.fretqty = ''
      if (this.dataForm.details.length > 0) {
        // 计算行号
        let len = this.dataForm.details.length - 1
        this.dataForm1.fline = this.dataForm.details[len].fline + 1
      } else {
        this.dataForm1.fline = 1
      }
    },
    yearup(date) {
      if (date === undefined || date === null) {
        return "";
      }
      return moment(date).format("YYYY-MM-DD");
    },
    hourup(date) {
      if (date === undefined || date === null) {
        return "";
      }
      return moment(date).format("HH:mm:ss");
    },
    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.dataForm.details.splice(this.dataForm.details.length-1,1);
          this.dataForm.frealbegtime = this.parserDate(
            this.yearup(this.dataForm.fplanusedate) +
            " " +
            this.hourup(this.dataForm.frealbegtime)
          );
          this.dataForm.frealendtime = this.parserDate(
            this.yearup(this.dataForm.fplanusedate) +
            " " +
            this.hourup(this.dataForm.frealendtime)
          );
          updateuseHead(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.fbillno === this.dataForm.fbillno) {
                  const index = this.list.indexOf(v);
                  this.list.splice(index, 1, this.dataForm);
                  break;
                }
              }
              this.dialogFormVisible = false;
              this.$notify.success({
                title: "成功",
                message: "更新物料申请主表成功",
              });
              this.selectList = [];
              this.flineList = [];
            })
            .catch((response) => {
              this.$notify.error({
                title: "失败",
                message: response.data.data,
              });
            });
        }
      });
    },
    audit(row) {
      this.$confirm('是否确定', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dataForm = Object.assign({}, row)
        checkBiz({ pBillNo: this.dataForm.fbillno, pBillState: 2, pBizType: 'i_tc_use_head', pUser: this.$store.state.user.id })
          .then(() => {
            for (const v of this.list) {
              if (v.fbillno === this.dataForm.fbillno) {
                this.dataForm.fbillstate = 2
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.dataForm)
                break
              }
            }
            this.$notify.success({
              title: '成功',
              message: '确认成功'
            })
          })
          .catch((response) => {
            this.$notify.error({
              title: '失败',
              message: response.data.data
            })
          })
      }).catch(() => { })
    },
    handleDelete(row) {
      this.$confirm("是否要删除物料申请主表", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteuseHead(row)
          .then((response) => {
            this.$notify.success({
              title: "成功",
              message: "删除物料申请主表成功",
            });
            const index = this.list.indexOf(row);
            this.list.splice(index, 1);
          })
          .catch((response) => {
            this.$notify.error({
              title: "失败",
              message: response.data.data,
            });
          });
      }).catch(() => { });
    },
    addData() {
      this.$refs["dataForm1"].validate((valid) => {
        this.dataForm1.fline = this.indexs;
        // 判断行号是否重复
        const flinetem = this.flineList.indexOf(this.dataForm1.fline);
        // 判断物料id是否重复
        const tem = this.selectList.indexOf(this.dataForm1.fgoodno);
        if (flinetem < 0) {
          if (tem < 0) {
            if (valid) {
              this.dialogFormVisible1 = false;
              this.dataForm.details.push(this.dataForm1);
              this.selectList.push(this.dataForm1.fgoodno);
              this.flineList.push(this.dataForm1.fline);
              this.indexs++;
            }
          } else {
            this.$notify.error({
              title: "失败",
              message: "所选物料重复",
            });
            return;
          }
        } else {
          this.$notify.error({
            title: "失败",
            message: "行号重复",
          });
          return;
        }
      });
    },

    cancel() {
      this.isshow = true;
      this.indexs = 1;
      this.dialogFormVisible = false;
      this.selectList = [];
      this.flineList = [];
      this.list.forEach((v) => {
        if (v.fbillno === this.dataForm.fbillno) {
          this.dataForm = this.listTmp;
          this.dataForm.details = this.detailsTmp;
          const index = this.list.indexOf(v);
          this.list.splice(index, 1, this.dataForm);
          return;
        }
      });
    },

    // 弹窗点击关闭前的回调
    handleClose() {
      this.isshow = true;
      this.indexs = 1;
      this.dialogFormVisible = false;
      this.selectList = [];
      this.flineList = [];
      this.list.forEach((v) => {
        if (v.fbillno === this.dataForm.fbillno) {
          this.dataForm = this.listTmp;
          this.dataForm.details = this.detailsTmp;
          const index = this.list.indexOf(v);
          this.list.splice(index, 1, this.dataForm);
          return;
        }
      });
    },

    handleUpdate1() {
      this.$nextTick(() => {
        this.$refs["dataForm1"].clearValidate();
      });
    },


    // 子表一添加编辑
    handleEdit1(row) {
      this.dataForm1 = Object.assign({}, row);
      this.dataForm1.fgoodname = this.formatfgoodno(row)
      this.dataForm1.fboxbarcodeName = this.formatfboxbarcode(row)
      this.dataForm1.fcabbarcodeName = this.formatfcabbarcode(row)
      // 清除验证
      this.$nextTick(() => {
        this.$refs["dataForm1"].clearValidate();
      });

    },
    // 子表一编辑保存数据
    editData1() {
      this.$refs["dataForm1"].validate((valid) => {
        if (valid) {
          if (this.dataForm.details.length > 0) {
            let temp = [...this.dataForm.details]
            let isRepeat = false
            // 子表编辑
            for (const v of this.dataForm.details) {
              if (v.fline === this.dataForm1.fline) {
                const index = this.dataForm.details.indexOf(v);
                // 判断物料是否重复
                temp.splice(index, 1);
                for (const vi of temp) {
                  if (vi.fgoodno == this.dataForm1.fgoodno) {
                    isRepeat = true
                    this.$notify.error({
                      title: '失败',
                      message: '所选物料重复'
                    })
                    return;
                  }
                }

                if (!isRepeat) {
                  if (this.dataForm1.fretqty > 0) {
                    if (this.dataForm1.fretqty > this.dataForm1.fqty) {
                      this.$notify.error({
                        title: '失败',
                        message: '申请量不能大于剩余量'
                      })
                      return
                    } else {
                      this.dataForm.details.splice(index, 1, this.dataForm1);
                      this.selectList.splice(index, 1, this.dataForm1.fgoodno);
                      this.isAdd1 = false
                      break;
                    }
                  } else {
                    this.$notify.error({
                      title: '失败',
                      message: '申请量必须大于0'
                    })
                    return
                  }

                }

              }
            }
            // 子表添加
            if (this.isAdd1) {
              // 判断行号是否重复
              const flinetem = this.flineList.indexOf(this.dataForm1.fline)
              // 判断物料id是否重复
              const tem = this.selectList.indexOf(this.dataForm1.fgoodno)
              if (flinetem < 0) {
                if (tem < 0) {
                  if (valid) {
                    if (this.dataForm1.fretqty > 0) {
                      if (this.dataForm1.fretqty > this.dataForm1.fqty) {
                        this.$notify.error({
                          title: '失败',
                          message: '申请量不能大于剩余量'
                        })
                        return
                      } else {
                        this.dataForm.details.push(this.dataForm1)
                        this.selectList.push(this.dataForm1.fgoodno)
                        this.flineList.push(this.dataForm1.fline)
                      }
                    } else {
                      this.$notify.error({
                        title: '失败',
                        message: '申请量必须大于0'
                      })
                      return;
                    }

                  }
                } else {
                  this.$notify.error({
                    title: '失败',
                    message: '所选物料重复'
                  })
                  return;
                }
              } else {
                this.$notify.error({
                  title: '失败',
                  message: '行号重复'
                })
                return;
              }
            }
          } else {
            // 子表第一次添加
            // 判断行号是否重复
            const flinetem = this.flineList.indexOf(this.dataForm1.fline)
            // 判断物料id是否重复
            const tem = this.selectList.indexOf(this.dataForm1.fgoodno)
            if (flinetem < 0) {
              if (tem < 0) {
                if (valid) {
                  if (this.dataForm1.fretqty > 0) {
                    if (this.dataForm1.fretqty > this.dataForm1.fqty) {
                      this.$notify.error({
                        title: '失败',
                        message: '申请量不能大于剩余量'
                      })
                      return
                    } else {
                      this.dataForm.details.push(this.dataForm1)
                      this.selectList.push(this.dataForm1.fgoodno)
                      this.flineList.push(this.dataForm1.fline)
                    }
                  } else {
                    this.$notify.error({
                      title: '失败',
                      message: '申请量必须大于0'
                    })
                    return;
                  }

                }
              } else {
                this.$notify.error({
                  title: '失败',
                  message: '所选物料重复'
                })
                return;
              }
            } else {
              this.$notify.error({
                title: '失败',
                message: '行号重复'
              })
              return;
            }
          }
          this.resetForm1()
          this.isAdd1 = true
          // 清除验证
          this.$nextTick(() => {
            this.$refs["dataForm1"].clearValidate();
          });
          // 计算行号
          if (this.dataForm.details.length > 0) {
            // 计算行号
            let len = this.dataForm.details.length - 1
            this.dataForm1.fline = this.dataForm.details[len].fline + 1
          } else {
            this.dataForm1.fline = 1
          }
          this.dataForm1.fretqty = ''
        }
      });
    },

    cancle1() {
      this.resetForm1()
      this.isAdd1 = true

      // 清除验证
      this.$nextTick(() => {
        this.$refs["dataForm1"].clearValidate();
      });

      // 计算行号
      if (this.dataForm.details.length > 0) {
        // 计算行号
        let len = this.dataForm.details.length - 1
        this.dataForm1.fline = this.dataForm.details[len].fline + 1
      } else {
        this.dataForm1.fline = 1
      }
      this.dataForm1.fretqty = ''
    },

    handleDelete1(row) {
      this.$confirm('是否要删除物料', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.dataForm.details.indexOf(row);
        this.dataForm.details.splice(index, 1);
        this.selectList.splice(index, 1);
        this.flineList.splice(index, 1);

        this.resetForm1()
        if (this.dataForm.details.length > 0) {
          // 计算行号
          let len = this.dataForm.details.length - 1
          this.dataForm1.fline = this.dataForm.details[len].fline + 1
        } else {
          this.dataForm1.fline = 1
        }
        this.dataForm1.fretqty = ''
      }).catch(() => { })
    },

    indexMethod(index) {
      index = index + 1;
      return index;
    },
    articel() {
      if (this.dataForm.fplanusedate == new Date) {
        return new Date.getHours
      }
      else {
        return '00:00'
      }
    }
  },
};
</script>
